# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os
import shutil
from conans import ConanFile, tools
from conan.tools.files import apply_conandata_patches, export_conandata_patches


class QemuDriversConan(ConanFile):
    name = "qemu_drivers"
    description = "some necessary drivers for qemu"
    topics = ("conan", "tools", "qemu_drivers")
    license = "GPL-2.0-or-later"
    homepage = "https://www.kernel.org/"
    url = "https://github.com/conan-io/conan-center-index"
    settings = "os", "arch", "compiler", "build_type"
    exports_sources = ["permissions.ini", "Makefile", "mock/*"]

    options = {
        "module_symvers": ["ANY"]
    }
    default_options = {
        "module_symvers": "",
    }

    def configure(self):
        pass

    def export_sources(self):

        export_conandata_patches(self)

    def source(self):
        # shutil.copy("/root/conan_index/linux.tar.gz", self.source_folder)
        tools.download(url=self.conan_data["sources"][self.version]['url'], filename='linux.tar.gz')
        tools.untargz(f'{self.source_folder}/linux.tar.gz',
                      self.source_folder, strip_root=True, pattern="net/9p/*")
        tools.untargz(f'{self.source_folder}/linux.tar.gz',
                      self.source_folder, strip_root=True, pattern="fs/9p/*")
        tools.untargz(f'{self.source_folder}/linux.tar.gz',
                      self.source_folder, strip_root=True, pattern="net/core/*")
        tools.untargz(f'{self.source_folder}/linux.tar.gz',
                      self.source_folder, strip_root=True, pattern="drivers/dma/*")
        tools.untargz(f'{self.source_folder}/linux.tar.gz',
                      self.source_folder, strip_root=True, pattern="drivers/block/*")
        tools.untargz(f'{self.source_folder}/linux.tar.gz',
                      self.source_folder, strip_root=True, pattern="drivers/virtio/*")
        tools.untargz(f'{self.source_folder}/linux.tar.gz',
                      self.source_folder, strip_root=True, pattern="drivers/net/*")

    def build(self):
        apply_conandata_patches(self)
        if self.settings.arch == "x86_64":
            return
        env_vars = {
            "RTOS_VERSION": self.version
        }
        with tools.environment_append(env_vars):
            self.run("make")

    def package(self):
        if self.settings.arch == "x86_64":
            return
        self.copy(
            "**/*.ko", dst=f'lib/modules/qemu/', keep_path=False)
        self.copy("permissions.ini")
